package com.asiainfo.ncrm.nfc;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.json.JSONException;
import org.json.JSONObject;
import org.jarjar.apache.commons.codec.digest.DigestUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.asiainfo.ncrm.R;
import com.ctsi.idcertification.BtReaderClient;
import com.ctsi.idcertification.CloudReaderClient;
import com.ctsi.idcertification.constant.Constant;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

@SuppressLint("NewApi")
public class NFCActivity extends Activity {

	private TextView tvError;
	//	private Button btn_bt;
//	private Button btn_otg;
//	private Button btn_nfc;
	private Button btnSure;
	IdCard_Bean bean;

	private Context mContext;
	
	NfcAdapter.ReaderCallback nfcCallBack;

	private Map resultMap;
	private ExecutorService pool = Executors.newCachedThreadPool();
	//private BtReaderClient bt_reader;
	private CloudReaderClient reader;
	private PendingIntent pendingIntent;
	private NfcAdapter nfcAdapter;
	private static IntentFilter[] FILTERS = { new IntentFilter(
			"android.nfc.action.TECH_DISCOVERED") };
	private static String[][] TECHLISTS = { { MifareClassic.class.getName() },
			{ NfcA.class.getName() }, { NfcB.class.getName() } };

	String appSecret_3des = "8D5964B8135DF69A8AA48F3F422814638D5964B8135DF69A"; // appId对应的加密密钥
	String appSecret = "86c2afa55bd747af89f4ebe10a72f4e3"; // appId对应的加密密钥
	String appId = "1025";
	String timestamp =String.valueOf( (new Date()).getTime());
	String nonce = "jfoiiuylkjljpohi";
	String businessExt = "{\"busiSerial\":\"\",\"staffCode\":\"110011\","
			+ "\"channelCode\":\"2001\",\"areaCode\":\"020\",\"teminalType\":\"andriod\","
			+ "\"srcSystem\":\"6003030001\",\"osType\":\"\",\"browserModel\":\"\","
			+ "\"clientIP\":\"\",\"deviceModel\":\"\",\"deviceSerial\":\"\"}";
	StringBuffer sbData = new StringBuffer();
	String signature = "";
	
	String resultBean="";
	
	int RETURNCODE=0;
	

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			int what = msg.what;
			String content_decryp = null;
			switch (what) {
			case 0:
				int resultCode = Integer.valueOf(resultMap.get(
						Constant.RESULT_MAP_KEY_FLAG).toString());
				if (resultCode == Constant.RESULT_OK) {
					String content = (String) resultMap
							.get(Constant.RESULT_MAP_KEY_CONTENT);
					try {
						content_decryp = Des33.decode1(content, appSecret_3des);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
//					tv_bt.setText(resultMap.get(Constant.STEP_MAP_KEY_FLAG)
//							+ "**********" + content_decryp);
					bean=getBean(content_decryp);
					resultBean= IdBeanToJson(bean);
					TextView tvName = (TextView) findViewById(R.id.tvName);
					tvName.setText(bean.partyName);
					TextView tvSex = (TextView) findViewById(R.id.tvSex);
					if ("0".equals(bean.gender)) {
						tvSex.setText("女");
					}else{
						tvSex.setText("男");
					}
					TextView tvNation = (TextView) findViewById(R.id.tvNation);
					tvNation.setText(bean.nation);
					TextView tvBornDay = (TextView) findViewById(R.id.tvBornDay);
					tvBornDay.setText(bean.bornDay);
					TextView tvCertAddress = (TextView) findViewById(R.id.tvCertAddress);
					tvCertAddress.setText(bean.certAddress);
					TextView tvCertNumber = (TextView) findViewById(R.id.tvCertNumber);
					tvCertNumber.setText(bean.certNumber);
					TextView tvCertOrg = (TextView) findViewById(R.id.tvCertOrg);
					tvCertOrg.setText(bean.certOrg);
					TextView tvEffDate = (TextView) findViewById(R.id.tvEffDate);
					tvEffDate.setText(bean.effDate+"-"+bean.expDate);
					//TextView tvExpDate = (TextView) pView.findViewById(R.id.tvExpDate);
					//tvExpDate.setText(bean.expDate);

					ImageView ivPhone = (ImageView) findViewById(R.id.ivPhone);
					if ((bean.identityPic!=null)&&(!"".equals(bean.identityPic))){
						FileOperationsJava fileOperationsJava=new FileOperationsJava();
						Bitmap bitmapPhone=fileOperationsJava.stringtoBitmap(bean.identityPic);
						if (bitmapPhone!=null){
							ivPhone.setImageBitmap(bitmapPhone);
						}
					}
				} else {
					String errmsg=resultMap.get(Constant.STEP_MAP_KEY_FLAG)
							+ "**********"
							+ "resultFlag:"
							+ String.valueOf(resultCode)
							+ "\n"
							+ "errorMsg: "
							+ ((String) resultMap
							.get(Constant.RESULT_MAP_KEY_ERRORMESSAGE));
					resultBean= (String) resultMap
							.get(Constant.RESULT_MAP_KEY_ERRORMESSAGE);
					tvError.setText(errmsg);
					Log.e("err",errmsg);
				}
				break;
			case 1:
				Toast.makeText(NFCActivity.this, "连接蓝牙失败", Toast.LENGTH_SHORT)
						.show();
				break;
			default:
				break;
			}

		}

	};
	
	public String IdBeanToJson(IdCard_Bean idbean){
		Map<String,Object> temp = new HashMap<String, Object>();
		if (idbean!=null) {
			String cust_name = idbean.partyName;
			String cust_num =idbean.certNumber;
			String cust_add = idbean.certAddress;
			String cust_image = idbean.identityPic;
			String cust_born = idbean.bornDay;
			String cust_nation = idbean.nation;
			String gender = idbean.gender;
			String certOrg = idbean.certOrg;
			String effDate= idbean.effDate;
			String expDate = idbean.expDate;
			
			temp.put("partyName", cust_name);
			temp.put("certNumber", cust_num);
			temp.put("certAddress", cust_add);
			temp.put("bornDay", cust_born);
			temp.put("identityPic", cust_image);
			temp.put("nation", cust_nation);
			temp.put("gender", gender);
			temp.put("certOrg", certOrg);
			temp.put("effDate", effDate);
			temp.put("expDate", expDate);
		}
		JSONObject json = new JSONObject(temp);
		
		return  json.toString();
	}

	protected IdCard_Bean getBean(String content_decryp) {
		IdCard_Bean bean=new IdCard_Bean();
		try {
			bean.bornDay=getTagValue(content_decryp,"bornDay");
			bean.certAddress=getTagValue(content_decryp,"certAddress");
			bean.certNumber=getTagValue(content_decryp,"certNumber");
			bean.certOrg=getTagValue(content_decryp,"certOrg");
			bean.effDate=getTagValue(content_decryp,"effDate");
			bean.expDate=getTagValue(content_decryp,"expDate");
			bean.gender=getTagValue(content_decryp,"gender");
			bean.identityPic=getTagValue(content_decryp,"identityPic");
			bean.nation=getTagValue(content_decryp,"nation");
			bean.partyName=getTagValue(content_decryp,"partyName");

			btnSure.setVisibility(View.VISIBLE);

		} catch (Exception e) {

			e.printStackTrace();
		}

		return bean;
	}

	public String getTagValue(String content,String tag){
		String tagStart="<"+tag+">";
		String tagEnd="</"+tag+">";
		int istart=content.lastIndexOf(tagStart);
		int iend=content.lastIndexOf(tagEnd);

		String result=content.substring(istart+tagStart.length(),iend);
		return result;

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cloud);
		
		mContext = this;
		
		ImageButton imb=(ImageButton) this.findViewById(R.id.ibRightButton);
		imb.setVisibility(View.GONE);
		tvError=(TextView) this.findViewById(R.id.tvError);
		btnSure=(Button) this.findViewById(R.id.btnSure);
		btnSure.setVisibility(View.GONE);

		//findViewByID();
		try {
			initData();
		} catch (JSONException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		initView();
		if (nfcAdapter == null) {
			Toast.makeText(this, "不支持nfc", Toast.LENGTH_LONG).show();
		} else if (!nfcAdapter.isEnabled()) {
			Toast.makeText(this, "nfc不可用", Toast.LENGTH_LONG).show();

		}
		initReaderCallback();
	}
	
	private String getlocalip(){  
        WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);    
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();    
        int ipAddress = wifiInfo.getIpAddress();   
        if(ipAddress==0)return null;  
        return ((ipAddress & 0xff)+"."+(ipAddress>>8 & 0xff)+"."  
                +(ipAddress>>16 & 0xff)+"."+(ipAddress>>24 & 0xff));  
    }  

	@Override
	protected void onResume() {
		super.onResume();
		if(nfcCallBack != null){
			reader.connect(Constant.READER_TYPE_NFC, nfcCallBack);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		reader.clear();
	}
	
	@SuppressLint("NewApi")
	private void initReaderCallback() {
		try {

			nfcCallBack = new NfcAdapter.ReaderCallback() {
				@Override
				public void onTagDiscovered(final Tag tag) {

					if (tag != null) {
						nfcAdapter
								.disableForegroundDispatch((Activity) mContext);
					}

					pool.execute(new Runnable() {
						@Override
						public void run() {
							signature = getSignature();

							Map resultMap = reader.CloudReadCert(appId,
									timestamp, nonce, businessExt, signature,
									Constant.READER_TYPE_NFC, tag);
							if (resultMap != null) {
								NFCActivity.this.resultMap = resultMap;
								handler.sendEmptyMessage(0);
							}
						}
					});
				}
			};
		} catch (NoClassDefFoundError e) {

		}
	}

//	@Override
//	protected void onNewIntent(final Intent intent) {
//		super.onNewIntent(intent);
//		if (tvError != null)
//			tvError.setText("");
//		if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
//			pool.execute(new Runnable() {
//				@Override
//				public void run() {
//					signature = getSignature();
//					Map resultMap = reader.CloudReadCert(appId, timestamp,
//							nonce, businessExt, signature,
//							Constant.READER_TYPE_NFC, intent);
//					if (resultMap != null) {
//						NFCActivity.this.resultMap = resultMap;
//						handler.sendEmptyMessage(0);
//					}
//				}
//
//			});
//		}
//
//	}

	private void initData() throws JSONException {
		// TODO Auto-generated method stub
		String device_model = Build.MODEL;   //璁惧鍨嬪彿
		String version_release = Build.VERSION.RELEASE;  //绯荤粺鐗堟湰鍙�
		TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);   
		String m_szImei = TelephonyMgr.getDeviceId(); //璁惧搴忓垪鍙�
		
		Intent i=getIntent();
		String param = i.getStringExtra("param");
		
		if(param == null || "".equals(param) || "[]".equals(param))
		{
			param = "[{\"channelCode\":\"6501041000105\",\"staffCode\":\"LUYW\",\"areaCode\":\"8650104\"}]";	
		}
		
		param = param.replace("[", "");
		param = param.replace("]", "");
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		
		JSONObject jsonObj = new JSONObject(businessExt);
		JSONObject paramObj = new JSONObject(param);
		jsonObj.put("areaCode", paramObj.get("areaCode"));
		jsonObj.put("channelCode", paramObj.get("channelCode"));
		jsonObj.put("staffCode", paramObj.get("staffCode"));
		jsonObj.put("deviceModel",device_model);
		jsonObj.put("deviceSerial",m_szImei);
		jsonObj.put("osType",version_release);
		jsonObj.put("clientIP",getLocalIpAddress());
		jsonObj.put("busiSerial",sdf.format(new Date()));
	
		businessExt = jsonObj.toString();
		nfcAdapter = NfcAdapter.getDefaultAdapter(this);
		pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
				getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

		//bt_reader = new BtReaderClient(NFCActivity.this);
		reader = new CloudReaderClient(NFCActivity.this);
	}
	
	public String getLocalIpAddress()  
    {  
        try  
        {  
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)  
            {  
               NetworkInterface intf = en.nextElement();  
               for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)  
               {  
                   InetAddress inetAddress = enumIpAddr.nextElement();  
                   if (!inetAddress.isLoopbackAddress())  
                   {  
                       return inetAddress.getHostAddress().toString();  
                   }  
               }  
           }  
        }  
        catch (Exception ex)  
        {  
            Log.e("WifiPreference IpAddress", ex.toString());  
        }  
        return null;  
    } 

	private String getSignature() {
		// TODO Auto-generated method stub
		timestamp = System.currentTimeMillis() + "";
		Log.i("timestamp", timestamp);
		sbData = new StringBuffer();
		sbData.append(appId).append(appSecret).append(businessExt)
				.append(nonce).append(timestamp);
		return DigestUtils.shaHex(sbData.toString());
	}

//	private void findViewByID() {
//		// TODO Auto-generated method stub
//		btn_bt = (Button) this.findViewById(R.id.btn_bt);
//		btn_otg = (Button) this.findViewById(R.id.btn_otg);
//		btn_nfc = (Button) this.findViewById(R.id.btn_nfc);
//		tv_bt = (TextView) this.findViewById(R.id.tv_btTest);
//	}

	private void initView() {
		// TODO Auto-generated method stub
		super.onStart();

		btnSure.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				pageSure(v);
			}
		});
		
		TextView tvTitleName = (TextView) this.findViewById(R.id.tvTitleName);
		tvTitleName.setText("NFC扫描身份证");
	}

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.main, menu);
//		return true;
//	}

	private Date str2Date(String str) {
		// TODO Auto-generated method stub

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d = null;
		try {
			d = sdf.parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return d;
	}

	public void pageSure(View v){
		Intent intent = getIntent();
		Bundle bundle = new Bundle();
		
//		bundle.putString("result", resultBean);//添加要返回给页面1的数据
//		Log.e("集团返回数据", resultBean);
//		bundle.putString("NAME", bean.partyName);
//		bundle.putString("SEX", bean.gender);
//		bundle.putString("BIRTHDAY", bean.bornDay);
//		bundle.putString("NATION", bean.nation);
//		bundle.putString("ADDRESS", bean.certAddress);
//		bundle.putString("NUM", bean.certNumber);
//		bundle.putString("IMAGE", bean.identityPic);
		
		bundle.putString("result", resultBean);
		Log.e("返回身份证类型", resultBean);
		intent.putExtras(bundle);
		this.setResult(RESULT_OK, intent);//返回页面1
		this.finish();

	}

	public void goBack(View v){
		this.finish();

	}


}
